package com.xnyzc.lhy.common.util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 转换工具类
 * @Author: scootXin
 * @Date: 2019/4/15 17:04
 */
public class BeanUtil {

    /**
     * 属性复制
     *
     * @param source
     * @param targetClass
     * @param <S>
     * @param <T>
     * @return
     */
    public static <S, T> T copyProperties(S source, Class<T> targetClass) {
        if (CheckUtil.objIsEmpty(source, targetClass)) {
            throw PangException.create(EErrorCode.missingArg);
        }

        try {
            T target = targetClass.newInstance();
            BeanUtils.copyProperties(source, target);

            return target;
        }
        catch (Exception e) {
            throw PangException.create(e);
        }
    }

    /**
     * 属性复制
     *
     * @param source
     * @param targetClass
     * @return
     */
    public static <S, T> IPage<T> copyProperties(IPage<S> source, Class<T> targetClass) {
        if (CheckUtil.objIsEmpty(source, targetClass)) {
            throw PangException.create(EErrorCode.missingArg);
        }

        IPage<T> targetPage = new Page<>();

        BeanUtils.copyProperties(source, targetPage, "records");

        if (CheckUtil.collectionIsNotEmpty(source.getRecords())) {
            List<T> collect = source.getRecords().parallelStream().map(s -> copyProperties(s, targetClass)).collect(Collectors.toList());

            targetPage.setRecords(collect);
        }

        return targetPage;
    }

    /**
     * 属性复制
     *
     * @param source
     * @return
     */
    public static <S, T> List<T> copyProperties(List<S> source, Class<T> targetClass) {
        if (CheckUtil.objIsEmpty(source, targetClass)) {
            throw PangException.create(EErrorCode.missingArg);
        }

        return source.parallelStream().map(s -> copyProperties(s, targetClass)).collect(Collectors.toList());
    }

    public static void main(String args[]) {
//        DActivity activity1 = new DActivity();
//        activity1.setActivityAddress("123");
//        activity1.setActivityId(1l);
//
//        DActivity activity2 = new DActivity();
//        activity2.setActivityAddress("223");
//        activity2.setActivityId(2l);
//
//        List<DActivity> activityList = Lists.newArrayList(activity1, activity2);
//
//        System.out.println(JSON.toJSONString(activityList));
//
//        System.out.println(JSON.toJSONString(BeanUtil.copyProperties(activityList, PActivity.class)));
    }


}
